﻿using BLL.Base;
using BLL.Basis;
using BLL.custom;
using BLL.sys;
using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.FrameEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BLL.BarCode
{
    /// <summary>
    /// 移动端接口业务逻辑方法
    /// </summary>
    public class ServiceBLL : PubMethod
    {
        Commands cmd;
        LoginInfo userLogin;
        Tools.TxtLogHelper txt;
        ReturnResult rsl;
        PieceRateBLL priceBLL;
        BarBLL barBLL;
        List<OperateModel> operList;
        OperateModel oper;
        CuDbHelper cuHelper;
        public ServiceBLL()
        {
            cmd = new Commands();
            userLogin = new LoginInfo();
            txt = new Tools.TxtLogHelper();
            priceBLL = new PieceRateBLL();
            barBLL = new BarBLL();
            cuHelper = new CuDbHelper();
        }


        /// <summary>
        /// 获取有效生产岗位
        /// </summary>
        /// <returns></returns>
        public ReturnResult getPositionInfo(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_ProductPosition_info where isdel=0 and gxCode='" + json["gxCode"] + "'");
                var table = cmd.GetDataTable(sb.ToString());
                List<string> rList = new List<string>();
                List<Dictionary<string, string>> dList = new List<Dictionary<string, string>>();
                foreach (DataRow r in table.Rows)
                {
                    if (!rList.Contains(r["pCode"].ToString()))
                    {
                        var dr = table.Select("pCode='" + r["pCode"].ToString() + "'");
                        Dictionary<string, string> dic = new Dictionary<string, string>();
                        dic["pCode"] = r["pCode"].ToString();
                        string contents = "", pCodes = ""; ;
                        foreach (DataRow row in dr)
                        {
                            contents += string.Format("{0}({1}),", row["gwName"].ToString(), row["persons"].ToString());
                            pCodes += string.Format("{0}-{1},", row["gwCode"].ToString(), row["persons"].ToString()); ;
                        }
                        dic["contents"] = contents.TrimEnd(',');
                        dic["pCodes"] = pCodes;
                        dList.Add(dic);
                        rList.Add(r["pCode"].ToString());
                    }
                }
                if (dList.Count > 0)
                {
                    rsl.Data = dList;
                    rsl.Result = true;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

       
        /// <summary>
        /// 获取账套名称
        /// </summary>
        /// <param name="account"></param>
        /// <param name="baseName"></param>
        private void getAccountName(string account, ref string baseName)
        {
            DbCustomBase cuBase = new DbCustomBase();
            cuBase.DbCode = account;
            cuBase.status = "Y";
            var list = cmd.GetDataByObject<DbCustomBase>(cuBase);
            if (list.Count > 0)
            {
                baseName = list[0].baseName;
            }
        }
        /// <summary>
        /// 获取客户参数数据
        /// </summary>
        /// <param name="parCode"></param>
        /// <param name="value"></param>
        private void getParametersInfo(string parCode, ref string value)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" select * from sys_parameters_info ");
            sb.Append(" where enable='open' and isDel=0 and parCode='" + parCode + "'");
            var table = cmd.GetDataTable(sb.ToString());
            if (table.Rows.Count > 0)
            {
                value = table.Rows[0]["parValue"].ToString();
            }
        }


        /// <summary>
        /// 发货单数据
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult SendOrderInfo(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" select top 100 dis.cDLCode,dis.cDepCode,dep.cDepName,cus.cCusCode,cus.cCusName,");
                sb.Append("dis.cPersonCode as personCode,per.cPersonName as personName,dis.dlid,");
                sb.Append(" Convert(varchar(10),dis.dDate,120) dDate from DispatchList dis ");
                sb.Append(" left join  Customer cus on cus.cCusCode=dis.cCusCode ");
                sb.Append(" left join  Person per on dis.cPersonCode = per.cPersonCode ");
                sb.Append(" left join Department dep on dis.cDepCode=dep.cDepCode ");
                sb.Append("  where isnull(dis.cVerifier,'') ='' and isnull(dis.dverifydate,'') =''  ");
                sb.Append(" order by dis.dDate desc,dis.cDLCode desc ");
                var table = new DataTable();
                table = cuHelper.getData(sb.ToString(), userLogin.UserInfo().baseCode);
                if (table.Rows.Count < 1)
                {
                    rsl.Message = "没有数据";
                    return rsl;
                }
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 发货单数据id
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult OrderList(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("SELECT l.cInvCode,p.cInvName,cInvStd,l.autoid,l.cWhCode,w.cWhName,cFree7  from DispatchLists l ");
                sb.Append("inner join inventory p on l.cInvCode=p.cInvCode ");
                sb.Append("inner join Warehouse w on w.cWhCode=l.cWhCode ");
                sb.Append("where l.dlid='" + dataId + "'");
                var table = cuHelper.getData(sb.ToString(), userLogin.UserInfo().baseCode);
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        public ReturnResult GetTradeMark_Packing_BoxSpec(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var o = JsonConvert.DeserializeObject<PrintInfoQuery>(json);

                var saleOrderDetailSql_template = @"SELECT * FROM SO_SODetails WHERE cSOCode = '{0}' and iRowNo = '{1}';";
                var saleOrderDetailSql = string.Format(saleOrderDetailSql_template, o.saleOrderCode, o.rowNo);

                var saleDetailDt = cuHelper.getData(saleOrderDetailSql, o.baseCode);

                var tradeMark = saleDetailDt.Rows[0]["cfree3"].ToString();
                var packing = saleDetailDt.Rows[0]["cDefine28"].ToString();

                //

                var invSql_template = @"SELECT * FROM Inventory WHERE cInvCode = '{0}';";
                var invSql = string.Format(invSql_template, o.proCode);

                var invDt = cuHelper.getData(invSql, o.baseCode);

                var boxSpec = invDt.Rows[0]["cInvDefine12"].ToString();

                var info = new PrintRequiredInfo
                {
                    tradeMark = tradeMark,
                    packing = packing,
                    boxSpec = boxSpec,
                };

                rsl.Data = info;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public ReturnResult MarchineRecords(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                if (!string.IsNullOrWhiteSpace(jsonStr))
                {
                    StringBuilder sb = new StringBuilder();
                    operList = new List<OperateModel>();
                    oper = new OperateModel();
                    var json = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonStr);
                    DbMachineRecord mr;
                    string mCode = String.Format("{0}/{1}", json["equipment"].ToString(), json["location"].ToString());
                    if (json["sensor"].ToString() == "zts")
                    {
                        #region 生产数
                        mr = new DbMachineRecord();
                        mr.createtime = getNow();
                        mr.number = json["value"].ToString();
                        mr.happenDate = getNowDate();
                        mr.id = Guid.NewGuid().ToString().Replace("-", "");
                        mr.mCode = mCode;
                        mr.dType = "RT";
                        mr.memo = "m-run";
                        oper.Data = mr;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                        #endregion
                    }
                    else if (json["sensor"].ToString() == "hd")
                    {
                        #region 设备运行状态
                        sb.Append("select id from sys_MachineRuning_records where mCode='" + mCode + "'");
                        sb.Append(" and happenDate='" + getNowDate() + "'");
                        var table = cmd.GetDataTable(sb.ToString());
                        mr = new DbMachineRecord();
                        oper = new OperateModel();
                        if (double.Parse(json["value"].ToString())==0)
                        {
                            mr.memo = "m-run";
                        }
                        else
                        {
                            mr.memo = "m-stop";
                        }
                        if (table.Rows.Count < 1)
                        {
                            mr.id = Guid.NewGuid().ToString().Replace("-", "");
                            mr.createtime = getNow();
                            mr.number = json["value"].ToString();
                            mr.happenDate = getNowDate();
                            mr.mCode = mCode;
                            mr.dType = "MT";
                            oper.Types = OperateModel.OperateType.Add;
                        }
                        else
                        {
                            mr.id = table.Rows[0]["id"].ToString();
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Conditions = "id";
                        }
                        #endregion
                        oper.Data = mr;
                        operList.Add(oper);
                    }
                    if (operList.Count > 0)
                    {
                        rsl = cmd.MoreUpdate(operList);
                        return rsl;
                    }
                    else
                    {
                        rsl.Result = true;
                        rsl.Message = "无需更新数据";
                    }
                
                }
                rsl.Message = "没有获取到数据";
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

    }

    public class PrintRequiredInfo
    {
        public string tradeMark { get; set; }
        public string packing { get; set; }
        public string boxSpec { get; set; }
    }

    public class PrintInfoQuery
    {
        public string baseCode { get; set; }
        public string saleOrderCode { get; set; }
        public string rowNo { get; set; }
        public string proCode { get; set; }
    }
}
